import random
import time
from datetime import datetime
import threading
import mysql.connector

# 数据库配置
DB_CONFIG = {
    'user': 'root',
    'password': 'Abcd@1234',
    'host': 'localhost',
    'database': 'data_shixun',
}


# 从数据库获取 opus_id 列表
def get_opus_ids():
    connection = mysql.connector.connect(**DB_CONFIG)
    cursor = connection.cursor()

    cursor.execute("SELECT opus_id FROM data_opus")  # 替换为你的表名
    opus_ids = [row[0] for row in cursor.fetchall()]  # 获取所有 opus_id

    cursor.close()
    connection.close()

    return opus_ids




# 随机生成请求方法
def generate_random_method():
    methods = ["GET"]
    return random.choice(methods)



# 生成日志条目
def generate_log_entry(opus_ids):
    user_id = random.randint(1000000, 9999999)   # 随机生成user_id 范围为1000000-9999999
    timestamp = datetime.now()  # 使用当前时间
    formatted_time = timestamp.strftime("%d/%b/%Y:%H:%M:%S")  # 格式化时间
    method = generate_random_method()
    system = random.choice(['IOS', 'Android', 'Windows', 'Mac', 'Linux', 'Others', 'HarmonyOS'])
    source = random.choice(['personal', 'financial', 'concern', 'featured', 'search', 'city', 'other'])
    fans = random.choice(['YES', 'NO'])
    thumb = random.choice(['YES', 'NO'])
    collection = random.choice(['YES', 'NO'])
    comment = random.choice(['YES', 'NO'])
    finash = random.choice(['YES', 'NO'])
    opus_id = random.choice(opus_ids)  # 从数据库中获取的 opus_id 中随机选择

    log_entry = f"{user_id} - - [{formatted_time}] \"{method}  HTTP/1.1\" {system} {source} {fans} opus_{opus_id} {thumb} {collection} {comment} {finash}\n"
    return log_entry


# 日志文件路径
log_file_path = 'user_behavior_logs.log'


# 持续生成日志并写入文件
def log_writer(opus_ids):
    with open(log_file_path, 'a') as log_file:  # 以追加模式打开文件
        while True:
            for _ in range(1):  # 每次生成5条日志
                log_entry = generate_log_entry(opus_ids)
                log_file.write(log_entry)  # 写入日志文件
            log_file.flush()  # 确保日志立即写入文件
            time.sleep(1)  # 每生成5条日志，暂停1秒


# 实时读取日志信息并显示
def log_reader():
    with open(log_file_path, 'r') as log_file:
        log_file.seek(0, 2)  # 移动到文件末尾
        while True:
            line = log_file.readline()
            if not line:
                time.sleep(0.1)  # 暂停一小会儿再检查
                continue
            print(line, end='')  # 输出新日志信息


# 启动日志生成和读取线程
if __name__ == "__main__":
    opus_ids = get_opus_ids()  # 从数据库获取 opus_id 列表
    writer_thread = threading.Thread(target=log_writer, args=(opus_ids,))
    reader_thread = threading.Thread(target=log_reader)

    writer_thread.start()
    reader_thread.start()

    writer_thread.join()
    reader_thread.join()